package com.lobobrowser.parser;



import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;

import com.lobobrowser.encoder.Encoder;
import com.lobobrowser.encoder.Key;





public class JavaFileParser {

	private File file;
	private Encoder encoder;
	private Key key;
	
	public JavaFileParser(File f){
		this.file = f;
		this.key = new Key(3);
		this.encoder = new Encoder(key);
	}
	
	public void TagSource (){
		StringBuilder text = new StringBuilder();
	    String NL = System.getProperty("line.separator");
	    Scanner scanner = null;
	    
	    try {
	     scanner = new Scanner(new FileInputStream(file));
	      while (scanner.hasNextLine()){
	        text.append(scanner.nextLine() + NL);
	      }
	    } catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    finally{
	      if(scanner !=null)  scanner.close();
	    }
	    
	    String source = text.toString();
	    
	    source = source.replaceAll("<head>", "<head><KEY" + key.getKey()+" />" );
	    source = source.replaceAll("<[\\s]*iframe[\\s]+", "<Encoded" + encoder.encode("iframe")+" ");
	    System.out.println(source);
	    
		FileWriter fstream = null;
		BufferedWriter out = null;
		
	    try {
	    	fstream = new FileWriter(file);
	        out = new BufferedWriter(fstream);
	        out.write(source);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
	      if(out !=null){
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	      }
	      if(fstream !=null){
				try {
					fstream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		      }
	    }
	    

	}
	
	public static void main(String [] args){
		File pFile = new File("C:/dev/workspace/testwebapp/src/com/test/Database.java");
		JavaFileParser tagger = new JavaFileParser(pFile);
		tagger.TagSource();
		
	
	

	}
}
